package cn.shyouchi.wuguanjia.android.components.retrofit;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;

import cn.shyouchi.wuguanjia.android.exception.ApiException;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import okhttp3.ResponseBody;
import retrofit2.Converter;


public class YouChiResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private Type type;

    public YouChiResponseBodyConverter() {

    }

    public YouChiResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        int code;
        String msg;
        try {

            String content = value.string();
            JSONObject contentJson = new JSONObject(content);
//            System.out.println("打印json数据："+content);


            LogUtil.json(content);

            code = contentJson.optInt("resultCode");
            if (contentJson.getInt("resultCode") == 0) {
                Gson gson=new Gson();

              //  return gson.fromJson(content,type);

               return JSON.parseObject(content,type);
            } else {
                throw new ApiException(code, "错误！");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new ApiException(-1, "服务器未知错误");
        } finally {
            value.close();
        }
    }

}
